#!/bin/bash
help()
{
	echo ---------------
	echo ----------------
	echo mongo的各表占用情况
	echo "-h|--host mongo的主机"
	echo "-d|--database 数据库名称"
}

tables() 
{
	#mongo $1/$2 --quiet --eval "db.getCollectionNames()"|grep -Eo '".*"'|sed 's/"//g'
	mongosh $1/$2 --quiet --eval "var a=db.getCollectionNames();for(var i in a){print(a[i])};process.exit()"
	#printjson()
}

tableInfo()
{
	mongosh $1/$2 --quiet --eval "var t=db.$3.stats();print(t.count+' '+t.totalIndexSize+' '+ (t.totalIndexSize+t.storageSize));process.exit()"
}

dbInfo()
{
	mongosh $1/$2 --quiet --eval "var d=db.stats();print(d.collections+' '+d.objects+' '+d.indexSize+' '+(d.storageSize+d.indexSize));process.exit()"
}

mongoScript() 
{
	mongo $1/$2 --quiet --eval "$3"
}

	#当$byte 大于是1024字节时，开始循环，当循环到第4次时跳出
	#echo $byte
#将Bytes,KB,MB,GB,TB定义成一维数组
sizeformat()
{
	i=0
	byte=$1
	while [ `echo "$byte>1024" | bc` -ne 0 ]
	do
		byte=`echo "scale=3;$byte/1024"|bc`
		i=$i+1
		case "$i" in
			4) break ;;
		esac
	done
	units=("Bytes" "KB" "MB" "GB" "TB")
	echo "$byte${units[$i]}"
}


_host=localhost
_database=''
# -n 报错时处理  带冒号表示后边需要指定值，双冒号指可选参数
GETOPT_ARGS=`getopt -o h:d: -l host:,database:,help -n "$0" -- "$@"`

#echo "$GETOPT_ARGS"
eval set -- "$GETOPT_ARGS"

while true
do
	case "$1" in
                -h|--host) _host=$2; shift 2;;
                -d|--database) _database=$2;shift 2;;
                --help) help; exit 1;;
                --) break ;;
                *) echo $1,$2,$show_usage; break ;;
        esac
done


_dbInfo=`dbInfo $_host $_database`
#indexSize=`echo $dbInfo|awk '{print $3}'`
#sizeformat $indexSize

echo 主 机: $_host
echo 数据库: $_database
echo 表总数: `echo $_dbInfo|awk '{print $1}'`
echo 数据量: `echo $_dbInfo|awk '{print $2}'`
_indexSize=`echo $_dbInfo|awk '{print $3}'`
echo 索引空间: `sizeformat $_indexSize`
echo 总空间: `sizeformat $(echo $_dbInfo|awk '{print $4}')`
echo 
echo =====================

printf "%25s %15s %15s %15s\n" collection count indexSize totalSize
echo ------------------------------------------------------------------
_tables=`tables $_host $_database`
_sort_tables=($(for t in $_tables
	do
	echo $t
	done | sort))
for t in ${_sort_tables[*]}
do
_info=(`tableInfo $_host $_database $t`)
#echo ${_info[*]}
#echo ${_info[2]}
printf "%25s %15s %15s %15s\n" $t ${_info[0]} `sizeformat ${_info[1]}` "`sizeformat ${_info[2]}`"
done
#echo 总数：$totalCount
#echo $str|awk '{printf $0}'
